#include <iostream>
using namespace std;
// Definition for singly-linked list.
typedef struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
    ~ListNode()
    {
        delete next; // 递归删除后续节点
    }

public:
    ListNode *add(int val)
    {
        this->next = new ListNode(val);
        return this->next;
    }
} ListNode;

class Solution
{
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
    {
        ListNode *head = new ListNode();
        ListNode *p = head;
        int carry = 0;
        while (l1 != nullptr || l2 != nullptr)
        {
            int sum = carry;
            if (l1 != nullptr)
            {
                sum += l1->val;
                l1 = l1->next;
            }
            if (l2 != nullptr)
            {
                sum += l2->val;
                l2 = l2->next;
            }
            carry = sum / 10;
            p->next = new ListNode(sum % 10); // 这里要new一个节点，不然会报错
            p = p->next;
        }
        if (carry > 0)
        { // 处理最后的进位
            p->next = new ListNode(carry);
        }
        return head;
    }
};

int main(int argc, char const *argv[])
{
    ListNode *l1 = new ListNode(2);
    l1->add(4)->add(3);
    ListNode *l2 = new ListNode(5);
    l2->add(6)->add(0);
    Solution s;
    ListNode *head = s.addTwoNumbers(l1, l2);
    delete l1,delete l2; // 释放链表内存
    ListNode *lsn = head->next; // 忽略头节点
    while (lsn != nullptr)
    {
        printf("%d ", lsn->val);
        lsn = lsn->next;
    }
    delete head; // 释放链表内存
    return 0;
}
